const {Menu,dialog} = require('electron')
const got = require('got').default
const path = require('path')
const imageType = require('image-type')
const randomstring = require('randomstring') // 生成随机字符串
const fs = require('fs')
const saveas = (srcUrl) => {
  if(srcUrl){
    const constMenu = Menu.buildFromTemplate([
      {
        label:'图片另存为...',
        click:()=>{
          got.get(srcUrl).then(async (response)=>{
            const chunk = Buffer.from(response.rawBody) // 将二进制数据转换为Buffer
            const imgType = imageType(chunk) // 获取图片类型
            //console.log(imgType.ext)
            const {filePath,canceled} = await dialog.showSaveDialog({
              title:'图片另存为',
              defaultPath:path.resolve(__dirname,'../public/uploads/' + randomstring.generate(16) + '.' + imgType.ext)
            })
            if(!canceled){
              fs.writeFileSync(filePath,chunk)
            }
          }).catch((e)=>{})
        },
        accelerator:'CmdOrCtrl+S' // 快捷键
      }
    ])
    constMenu.popup()
  }
}
module.exports = saveas